<?php

/**
 * post 同步类型 
 */
class PostsynService {

	public $dbutil;		//本站db连接
	
	public $wpDbUtil;	//wp站db连接
	
	function __construct($dbutil){
		$this->dbutil =  $dbutil;
		global $CONFIG;
		$this->wpDbUtil = new DbUtil($CONFIG['DB_WP']['db_host'], $CONFIG['DB_WP']['db_user'], 
	    	$CONFIG['DB_WP']['db_password'], $CONFIG['DB_WP']['db_database']);
	}
	
    function syn(){

    	$result = $this->dbutil->get_results("select * from post_category ");
    	//缓存类型
    	$category = array();
    	foreach($result as $re){
    		$category[$re->category_id] = $re->category_name;
    	}
    	
    	$wpCategory = array();
    	//缓存wp类型到term_taxonomy
    	$sql = "select tt.term_taxonomy_id, st.term_id ,st.name ,tt.parent from wp_terms st " .
    			"JOIN wp_term_taxonomy tt on st.term_id = tt.term_id where tt.taxonomy = 'category';";
    	$result = $this->wpDbUtil->get_results($sql);
    	foreach($result as $re){
    		$wpCategory[$re->name] = $re->term_taxonomy_id;
    	}
    	
    	$time = date("Y-m-d",strtotime("-3 day")); 
    	$sql = "select *,DATE_FORMAT(post_date,'%Y-%m-%d %H:%i:%s') as pd from posts where post_date >= str_to_date('$time','%Y-%m-%d')";
    	$result = $this->dbutil->get_results($sql);
    	$synData = array();
    	
    	$total = 0 ;
    	if($result != null){
    		
    		foreach($result as $re){

				//检测post是否已经存在
    			$title = $re->post_title;
    			$sql = "select * from wp_posts where post_type = 'post' and post_title = '$title' ";
    			$data = $this->wpDbUtil->get_row($sql);
    			if($data != null && count($data) > 0 ){
    				continue;
    			}
    			
    			//获取post数据
    			$content = $re->post_content;
    			$content = str_replace("<img","<img style=\'display:none\' ",$content);
    			
    			$author = $re->post_author;
    			$pd = $re->pd;
    			
    			//插入post数据
    			$insertSql = "insert into wp_posts(post_title,post_content,post_type,post_author,post_date,post_date_gmt,post_modified,post_modified_gmt) values " .
    					" ('$title','$content','post','$author',str_to_date('$pd','%Y-%m-%d %H:%i:%s'),str_to_date('$pd','%Y-%m-%d %H:%i:%s'),str_to_date('$pd','%Y-%m-%d %H:%i:%s'),str_to_date('$pd','%Y-%m-%d %H:%i:%s') )";
    			$this->wpDbUtil->query($insertSql);

    			//插入post类型
    			//获取post id
    			$data = $this->wpDbUtil->get_row($sql);
    			$postId = $data->ID;
    			//获取term_taxonomy
    			$catName = $category[$re->post_category];
    			$catId = null;
    			if($catName != null && $wpCategory[$catName] != null){
    				$catId = $wpCategory[$catName];
    				$insertSql = " insert into wp_term_relationships (object_id,term_taxonomy_id) values ('$postId','$catId') ";
    				$this->wpDbUtil->query($insertSql);
    			}
    			$total++;
    			
    		}
    	}
    	return $total;
    }
}
?>